<!-- 图片上传组件 -->
<template>
  <el-upload
    ref="fileUpload"
    class="avatar-uploader"
    multiple
    :action="baseURL + '/system/oss/upload'"
    :before-upload="handleBeforeUpload"
    :headers="{ Authorization: getToken() }"
    :file-list="fileList"
    :limit="limit"
    list-type="picture-card"
    :on-error="handleUploadError"
    :on-exceed="handleExceed"
    :on-success="handleUploadSuccess"
    :on-remove="handleRemove"
  >
    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    <template #tip>
      <div v-if="isShowTip" class="el-upload__tip">
        <slot name="tip">
          请上传
          <template v-if="fileSize">
            大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
          </template>
          <template v-if="fileType">
            格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
          </template>
          的文件
        </slot>
      </div>
    </template>
  </el-upload>
</template>

<script setup lang="ts">
import { ref, toRefs, type Ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus';
import { deleteFile } from '@/api/systems';
import { baseURL } from '@/utils/axios';
import { getToken } from '@/utils/utils';

const imageUrl = defineModel('imageUrl') as Ref<string>;

const props = defineProps({
  // 值
  // eslint-disable-next-line vue/require-default-prop
  value: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 5
  },
  // 文件类型
  fileType: {
    type: Array,
    default: () => ['png', 'jpg', 'jpeg']
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
});
const { fileSize, limit, fileType, isShowTip } = toRefs(props);

const defaultFileList = imageUrl.value ? [{ url: imageUrl.value, name: '' }] : [];

const fileList = ref<UploadUserFile[]>(defaultFileList);

// 上传前校检格式和大小
const handleBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  const fileNames = rawFile.name.split('.');
  const curFileType = fileNames[fileNames.length - 1];
  // 校检文件类型
  if (!fileType.value.includes(curFileType)) {
    ElMessage.error(`文件格式不正确, 请上传${fileType.value.join('/')}格式文件!`);
    return false;
  } else if (rawFile.size / 1024 / 1024 > fileSize.value) {
    ElMessage.error(`文件不能超过${fileSize.value}MB!`);
    return false;
  }
  return true;
};

// 文件个数超出
const handleExceed = () => {
  ElMessage.error(`上传文件数量不能超过 ${limit.value} 个!`);
};

// 上传失败
const handleUploadError = () => {
  ElMessage.error('上传文件失败，请重试');
};

// 上传成功回调
const handleUploadSuccess: UploadProps['onSuccess'] = (res) => {
  if (res.code === 200) {
    fileList.value.push(res.data);
    imageUrl.value = res.data.url;
  } else {
    ElMessage.error(res.mag);
  }
};

// 移除文件的时候 删除
const handleRemove: UploadProps['onRemove'] = (file: any) => {
  if (file.response) {
    deleteFile(file.response?.data.ossId);
  }
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
